package com.yiwenAI.service.impl;

import com.yiwenAI.dao.SentenceDao;
import com.yiwenAI.dao.UserDao;
import com.yiwenAI.entity.Sentence;
import com.yiwenAI.entity.User;
import com.yiwenAI.entity.Word;
import com.yiwenAI.service.UserService;
import com.yiwenAI.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ZhaoShihao
 * @version 1.0
 * @create 2017-04-07 15:19
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private SentenceDao sentenceDao;

    @Override
    public User login(String username, String password) {
        password = StringUtil.getPassword(password);
        return userDao.selectUserForLogin(username, password);
    }

    @Override
    public Sentence getOneSentence(Integer userId,Integer count) {
        Sentence sentence = sentenceDao.selectSentenceByRandom(userId, count);
        if (sentence!=null){
            Integer id = sentence.getId();
            sentenceDao.addSentenceCount("assigned_num",id);
        }else {
            sentence=new Sentence();
            sentence.setId(-1);
        }
        return sentence;
    }

    @Override
    @Transactional
    public User submitWords(Integer userId, Integer sentenceId, String words) {
        userDao.addUserCount("split_num",userId);
        sentenceDao.addSentenceCount("submit_num",sentenceId);
        int i = sentenceDao.insertWords(new Word(words, sentenceId));
        Word word = sentenceDao.selectWordsNum(words);
        sentenceDao.insertUserWord(userId,word.getId());
        if (i<1){
            sentenceDao.updateWordsNum(words);
            if ((word.getWordsNum()+1) >=3) {
                // TODO: 2017/4/8 0008 加入词组库，等待下次分词 
                sentenceDao.updateSentence(new Sentence(sentenceId, words));
                userDao.addUserCount("accepted_num", userId);
            }
        }
        return userDao.selectUserById(userId);
    }

    @Override
    public int updatePwd(Integer userId, String oldPwd, String newPwd) {
        oldPwd=StringUtil.getPassword(oldPwd);
        newPwd=StringUtil.getPassword(newPwd);
        return userDao.updateUserPassword(userId,newPwd,oldPwd);
    }
}
